package main

import (
	"context"
	bark "go_final/demos/grpc_validator/protofile"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type Greeter struct{}

func (g Greeter) SayHello(ctx context.Context, person *bark.Person) (*bark.Person, error) {
	return &bark.Person{
		Id: 32,
	}, nil
}

type Validator interface {
	Validate() error
}

func main() {
	/** 测试validate的调用
	p := new(bark.Person)
	p.Id = 1000
	err := p.Validate()
	if err != nil {
		panic(err)
	}
	*/

	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler) (resp interface{}, err error) {
		if r, ok := req.(Validator); ok {
			if err := r.Validate(); err != nil {
				return nil, status.Error(codes.InvalidArgument, err.Error())
			}
		}
		return handler(ctx, req)
	}
	opt := grpc.UnaryInterceptor(interceptor)

	s := grpc.NewServer(opt)

	bark.RegisterBarkServer(s, &Greeter{})
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}
	s.Serve(lis)
}
